<template>
  <div class="charts-wrap">
    <div class="charts-wrap-item">
      <div class="charts-box">
        <div class="charts-title">
          <h2>收入统计</h2>
        </div>
        <div class="charts-info">
          <div class="total-revenue">
            <p v-if="dateFlag">
              该年总收入：
              <span>{{yearTotal}}</span>
            </p>

            <p v-else>
              该月总收入：
              <span>{{monthTotal}}</span>
            </p>
          </div>
          <div class="charts-info-right">
            <el-select
              class="charts-info-select"
              size="mini"
              v-model="reqParams.year"
              @change="yearChange"
              filterable
            >
              <el-option v-for="item in yearList" :key="item" :label="item" :value="item" />
            </el-select>
            <el-select
              v-if="!dateFlag"
              class="charts-info-select-month"
              size="mini"
              v-model="reqParams.month"
              @change="monthChange"
              filterable
            >
              <el-option v-for="item in monthList" :key="item" :label="item" :value="item" />
            </el-select>
            <div class="charts-info-btn">
              <div class="charts-info-btn-box">
                <div
                  class="charts-info-btn-year charts-info-btn-item"
                  :class="{'charts-info-btn-active':dateFlag}"
                  @click="dateHandle(1)"
                >每年</div>
                <div
                  class="charts-info-btn-month charts-info-btn-item"
                  :class="{'charts-info-btn-active':!dateFlag}"
                  @click="dateHandle(0)"
                >每月</div>
              </div>
            </div>
          </div>
        </div>
        <div
          v-loading="loading"
          element-loading-text="加载中..."
          element-loading-spinner="el-icon-loading"
          id="income-chart"
          class="income-chart"
          :style="{width: '100%', height: '100%'}"
        />
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { getIncomeData } from "@/api/homepage";
export default {
  name: "IncomeChart",
  data() {
    return {
      loading: false,
      yearTotal: "",
      monthTotal: "",
      yearIncomeData: [],
      monthIncomeData: [],
      yearList: [],
      monthList: [
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "9",
        "10",
        "11",
        "12"
      ],
      dateList: [],
      data: [],
      dateFlag: 1,
      reqParams: {
        year: "",
        month: ""
      }
    };
  },
  created() {
    this.getNowData();
    this.getYearList();
    this._getIncomeData();
  },
  mounted() {
    // for (let i = 1; i < 31; i++) {
    //   this.dateList.push(i);
    // }
    // console.log("日期", this.dateList);
  },
  computed: {},
  methods: {
    // 获取当前年月
    getNowData() {
      this.reqParams.year = new Date().getFullYear();
      this.reqParams.month = new Date().getMonth() + 1;
    },
    // 获取年份列表
    getYearList() {
      let myDate = new Date();
      let thisYear = myDate.getFullYear(); // 获取当年年份
      let Section = thisYear - 2008; // 声明一个变量 获得当前年份至想获取年份差 eg.2008
      for (var i = 0; i <= Section; i++) {
        this.yearList.push(thisYear--);
      } // 遍历并添加年份到数组
      // console.log("年份", this.yearList);
    },
    // 选择年份
    yearChange(val) {
      this.reqParams.year = val;
      this._getIncomeData();
    },
    // 选择月份
    monthChange(val) {
      this.reqParams.month = val;
      this._getIncomeData();
    },
    _getIncomeData() {
      this.loading = true;
      this.yearIncomeData = [];
      this.monthIncomeData = [];
      // console.log("请求收入图表参数", this.reqParams);
      getIncomeData(this.reqParams).then(res => {
        // console.log("请求收入数据", res);
        this.loading = false;
        let monthLisy = JSON.parse(res.data.month_list);
        let yearLisy = JSON.parse(res.data.year_list);
        for (let key in yearLisy) {
          // console.log(key);
          // console.log(this.yearIncomeData[key]);
          this.yearIncomeData.push(yearLisy[key]);
        }
        for (let key in monthLisy) {
          // console.log(key);
          // console.log(this.yearIncomeData[key]);
          this.monthIncomeData.push(monthLisy[key]);
        }
        this.yearTotal = this.yearIncomeData[0];
        this.monthTotal = this.monthIncomeData[0];
        this.yearIncomeData.shift();
        this.monthIncomeData.shift();
        this.dateList = [];
        for (let i = 1; i <= this.monthIncomeData.length; i++) {
          this.dateList.push(i);
        }
        // console.log("年数据", this.yearIncomeData);
        // console.log("月数据", this.monthIncomeData);
        if (this.yearIncomeData && this.monthIncomeData) {
          this.drawLine();
        }
      });
    },
    dateHandle(falg) {
      this.dateFlag = falg;
      this.drawLine();
    },

    drawLine() {
      let myChart = this.echarts.init(document.getElementById("income-chart")); // 绘制图表
      myChart.setOption({
        tooltip: {},
        legend: {
          data: "",
          icon: "triangle", //  这个字段控制形状  类型包括 circle，rect ，roundRect，triangle，diamond，pin，arrow，none
          itemWidth: 40, // 设置宽度
          itemHeight: 5, // 设置高度
          itemGap: 10 // 设置间距
          // textStyle:{
          //     fontSize: 18,//字体大小
          //     color: '#404040'//字体颜色
          // },
        },
        xAxis: {
          name: this.dateFlag ? "月份" : "日期",
          nameTextStyle: {
            padding: [30, 0, 0, 0], // 四个数字分别为上右下左与原位置距离
            color: "#999"
          },
          type: "category",
          data: this.dateFlag ? this.monthList : this.dateList,
          splitLine: {
            // 设置网格线
            show: true, // 是否显示
            lineStyle: {
              type: "dashed", // 设置网格线类型 dotted：虚线   solid:实线
              color: "#E6EFF2"
            }
          },
          axisTick: {
            // 设置坐标轴 刻度
            show: false, // 是否显示
            inside: true, // 是否朝内
            length: 3, // 长度
            lineStyle: {
              // 默认取轴线的样式
              color: "red",
              width: 1,
              type: "solid"
            }
          },
          axisLine: {
            // 坐标轴 轴线
            show: true, // 是否显示
            symbol: ["none"], // 是否显示轴线箭头
            symbolSize: [8, 8], // 箭头大小
            symbolOffset: [0, 7], // 箭头位置
            // ------   线 ---------
            lineStyle: {
              // 设置y轴轴线样式
              color: "#AADEF2",
              width: 1,
              type: "solid"
            }
          },
          axisLabel: {
            textStyle: {
              // 设置X轴字体
              color: "#999999",
              width: "100%",
              align: "left"
            }
          }
        },
        yAxis: {
          name: "金额（元）",
          nameTextStyle: {
            padding: [0, 0, 10, -50], // 四个数字分别为上右下左与原位置距离
            color: "#999"
          },
          type: "value",
          max: 20000,
          min: 0,
          splitNumber: 8,
          splitLine: {
            // 设置网格线
            show: true, // 是否显示
            lineStyle: {
              type: "solid", // 设置网格线类型 dotted：虚线   solid:实线
              color: "#CEE8F2"
            }
          },
          axisTick: {
            // 坐标轴 刻度
            show: false, // 是否显示
            inside: true, // 是否朝内
            length: 3, // 长度
            lineStyle: {
              // 默认取轴线的样式
              color: "red",
              width: 1,
              type: "solid"
            }
          },
          axisLabel: {
            textStyle: {
              // 设置y轴字体
              color: "#404040"
            }
          },
          axisLine: {
            // 坐标轴 轴线
            show: true, // 是否显示
            symbol: ["none"], // 是否显示轴线箭头
            symbolSize: [8, 8], // 箭头大小
            symbolOffset: [0, 7], // 箭头位置
            // ------   线 ---------
            lineStyle: {
              // 设置y轴轴线样式
              color: "#AADEF2",
              width: 1,
              type: "solid"
            }
          }
        },
        series: [
          {
            type: "line",
            symbolSize: 7,
            data: this.dateFlag ? this.yearIncomeData : this.monthIncomeData,
            symbol: "emptyCircle",
            itemStyle: {
              normal: {
                color: "#FEB783",
                borderColor: "#FF770F", // 拐点边框颜色
                lineStyle: {
                  width: 3 // 设置线条粗细
                }
              }
            },
            areaStyle: {
              normal: {
                color: {
                  type: "linear", //设置线性渐变
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    {
                      offset: 0,
                      color: "#FFF5E7" // 0% 处的颜色
                    },
                    {
                      offset: 1,
                      color: "#FFF" // 100% 处的颜色
                    }
                  ],
                  globalCoord: false // 缺省为 false
                }
              }
            }
          }
        ]
      });
      // 修改canvas及其父级的宽高为百分比自适应
      const $canvas = $("#income-chart").find("canvas");
      $canvas.width("100%");
      $canvas.parent().width("100%");
    }
  }
};
</script>

<style lang="scss" >
.charts-wrap {
  width: 59%;
  height: 100%;
  background: #fff;
}
.charts-wrap-item {
  width: 102%;
  height: 95%;
  position: relative;
}
.charts-box {
  width: 100%;
  height: 90%;
  margin: 0 auto;
  margin-top: 17px;
}

.charts-title {
  text-align: center;
  font-size: 16px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  color: rgba(51, 51, 51, 1);
}

.charts-info {
  width: 88%;
  margin-left: 40px;
  display: flex;
  justify-content: space-between;
}
.total-revenue {
  font-size: 16px;
  color: #333;
  line-height: 0;
}

.total-revenue span {
  color: #48b0fa;
}
.charts-info-right {
  display: flex;
}
.charts-info-select {
  width: 92px;
  position: relative;
  margin-right: 8px;
}
.charts-info-select-month {
  width: 72px;
  position: relative;
}
.charts-info-select .el-input,
.charts-info-select-month .el-input {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
.charts-info-btn {
  margin-left: 10px;
  font-size: 14px;
  width: 130px;
  height: 100%;
  line-height: 28px;
  position: relative;
}
.charts-info-btn-box {
  display: flex;
  width: 100%;
  height: 28px;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
.charts-info-btn-year,
.charts-info-btn-month {
  width: 50%;
  height: 100%;
  text-align: center;
  cursor: pointer;
}

.charts-info-btn-item {
  border: 1px solid #fe9f1d;
  color: #fe9f1d;
}

.charts-info-btn-item:hover {
  background: #fff5ed;
}

.charts-info-btn-active {
  background: #ff7f5b;
  border: 1px solid #ff7f5b;
  color: #fff;
}

.charts-info-btn-active:hover {
  background: #ff7f5b;
}

.charts-info-btn-month {
  border-radius: 0 20px 20px 0;
}

.charts-info-btn-year {
  border-radius: 20px 0 0 20px;
}

// .income-chart div canvas {
//   width: 982px !important;
//   height: 460px !important;
// }
</style>

